package com.yuntsg.nnsfcp.service.front.ut;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 存储用户对页面的点击, 避免操作过快. 重复提交
 *
 * @author ：ljx
 * @date ：Created in 2019/9/14
 */
@Slf4j
public class QuickRequestHandler implements Serializable {

    private static Map<String, Map<String, Long>> URL_MAP = new HashMap<>(16);

    /**
     * 获取请求地址的时间
     *
     * @param userId     用户id
     * @param requestUrl 请求地址
     * @return 太快返回false
     */
    public static boolean getRequestUrlTime(String userId, String requestUrl) {
        try {
            Long currentTime = System.currentTimeMillis();
            //频繁点击处理
            if (URL_MAP.get(userId) != null) {
                Map<String, Long> userMap = URL_MAP.get(userId);
                if (userMap.get(requestUrl) != null) {
                    Long aLong = userMap.get(requestUrl);
                    long resultTime = currentTime - aLong;
                    userMap.put(requestUrl, currentTime);
                    if (resultTime < 300) {
                        return false;
                    }
                } else {
                    userMap.put(requestUrl, currentTime);
                    URL_MAP.put(userId, userMap);
                }
            }
            HashMap<String, Long> map = new HashMap<>();
            map.put(requestUrl, currentTime);
            URL_MAP.put(userId, map);
            return true;
        } catch (Exception e) {
            log.error("频繁点击处理出现错误");
            e.printStackTrace();
        }
        return false;
    }


    @Scheduled(cron = "0 0 0 * * *")
    public void createMap() {
        log.info("清除存储requestUrl的Map");
        URL_MAP = new HashMap<>(16);
    }
}
